#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <errno.h>

typedef struct Usr
{
	int iId;
	char caName[32];
	float fScore;

	struct Usr *next;
}Usr;

typedef struct List
{
	int iLen;
	Usr *pFirstNode;
}List;

Usr *mkUsrNode()
{
	Usr *node = (Usr*)malloc(sizeof(Usr));
	if (NULL == node)
	{
		exit(EXIT_FAILURE);
	}
	memset(node, 0, sizeof(Usr));
	return node;
}

List *mkList()
{
	List *list = (List*)malloc(sizeof(List));
	if (NULL == list)
	{
		exit(EXIT_FAILURE);
	}
	memset(list, 0, sizeof(List));
	return list;
}

void insert(List *list, Usr *node)
{
	if (NULL == list || NULL == node)
	{
		return;
	}
	node->next = list->pFirstNode;
	list->pFirstNode = node;	
	list->iLen++;
}

void display(const List *list)
{
	if (NULL == list)
	{
		return;
	}

	Usr *node = list->pFirstNode;
	while (NULL != node)
	{
		printf("id=%d,name=%s,score=%.1f\n"
			   , node->iId, node->caName, node->fScore);
		node = node->next;
	}
}

void input(Usr *node)
{
	if (NULL == node)
	{
		return;
	}
	printf("请输入人员信息id,name,score:\n");
	scanf("%d%s%f", &node->iId, node->caName
					, &node->fScore);
}

void sortByScore(List *list)
{
	if (NULL == list)
	{
		return;
	}
	Usr *pre = NULL;
	Usr *cur = NULL;
	int i=0;
	int j=0;
	for (; i<list->iLen; i++)
	{
		pre = list->pFirstNode;
		cur = pre;
		for (j=0; j<list->iLen-1; j++)
		{
			if (cur->fScore > cur->next->fScore)
			{
				if (cur == list->pFirstNode)
				{
					list->pFirstNode = cur->next;	
					cur->next = cur->next->next;
					list->pFirstNode->next = cur;
					pre = list->pFirstNode;
					continue;
				}
				else
				{
					pre->next = cur->next;
					cur->next = cur->next->next;	
					pre->next->next = cur;
					pre = pre->next;
					continue;
				}
			}	
			pre = cur;
			cur = cur->next;
		}
	}
}

void load(List *list, const char *path)
{
	if (NULL == list || NULL == path)
	{
		return;
	}
	FILE *file = fopen(path, "r");
	Usr *node = NULL;
	int ret = 0;
	while (1)
	{
		node = mkUsrNode();
		ret = fscanf(file, "%d%s%f", &node->iId
					     , node->caName
						 , &node->fScore);
		if (0 >= ret)
		{
			free(node);
			node = NULL;
			fclose(file);
			break;
		}
		insert(list, node);
	}
}

void save(List *list, const char *path)
{
	if (NULL == list || NULL == path)
	{
		return;
	}
	FILE *file = fopen(path, "wb");
	if (NULL == file)
	{
		printf("open %s failed --> %s\n"
			   , path, strerror(errno));
		exit(EXIT_FAILURE);
	}

	Usr *node = list->pFirstNode;
	while (NULL != node)
	{
		fwrite(node, sizeof(Usr), 1, file);
		node = node->next;
	}
	fclose(file);
}

// ./a.out  usr.info   usr.bak
int main(int argc, char *argv[])
{	
	if (3 != argc)
	{
		exit(EXIT_FAILURE);
	}

	List *list = mkList();
	
	load(list, argv[1]);

	display(list);
	sortByScore(list);
	printf("----------------------\n\n");
	display(list);
	save(list, argv[2]);

	return 0;
}
